package sixkey.controller;

/**
 * ClassName:AlipayController
 * Package:sixkey.controller
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/6/26 - 23:16
 * @Version:v1.0
 */

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import sixkey.config.AlipayConfig.AlipayConfig;
import sixkey.utils.ResResult;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码支付
 */
@Api(tags = "二维码支付")
@RestController
public class AlipayController {

    /*@RequestMapping(value = "index")
    public String payCoin(){
        return "index.html";
    }*/


    /**
     * 支付宝扫码支付
     */
    @ApiOperation(value = "支付宝扫码支付")
    @PostMapping("/scan/pay")
    public String scanPay(@RequestParam("outTradeNo") String outTradeNo,@RequestParam("subject") String subject,@RequestParam("totalAmount") String totalAmount) throws AlipayApiException {
        // 创建AlipayClient对象
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAY, AlipayConfig.APPID, AlipayConfig.APPPRIVATEKEY, "json", "utf-8", AlipayConfig.ALIPAYPUBLICKEY, "RSA2");
        // 创建AlipayTradePrecreateRequest对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 设置异步通知地址
        request.setNotifyUrl(AlipayConfig.NOTIFYURL);
        // 设置订单信息
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(totalAmount);
        model.setSubject(subject);
        request.setBizModel(model);
        // 发起支付请求
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            // 返回二维码链接给前端
            return response.getQrCode();
        } else {
            // 处理支付失败的情况
            throw new AlipayApiException(response.getMsg());
        }
    }

    /**
     * 处理支付结果
     */
    @PostMapping("/notify")
    public ResResult notify(HttpServletRequest request) throws AlipayApiException {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                valueStr.append((i == values.length - 1) ? values[i] : values[i] + ",");
            }
            params.put(name, valueStr.toString());
        }
        // 验证签名
        boolean verifyResult = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAYPUBLICKEY, "UTF-8", "RSA2");
        if (verifyResult) {
            // 处理支付成功的情况
            String orderNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String amount = params.get("total_amount");
            // TODO: 处理订单状态
            return ResResult.okResult();
        } else {
            // 处理验签失败的情况
            return ResResult.errorResult();
        }
    }
}
